package com.qf.rbac.sys.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.qf.rbac.sys.entity.SysRole;
import com.qf.rbac.sys.mapper.SysRoleMapper;
import com.qf.rbac.sys.service.ISysRoleDeptService;
import com.qf.rbac.sys.service.ISysRoleMenuService;
import com.qf.rbac.sys.service.ISysRoleService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.qf.rbac.utils.PageQueryUtil;
import com.qf.rbac.utils.PageVo;
import net.bytebuddy.asm.Advice;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.Map;

/**
 * <p>
 * 角色 服务实现类
 * </p>
 *
 * @author dongjl
 * @since 2022-04-16
 */
@Service
public class SysRoleServiceImpl extends ServiceImpl<SysRoleMapper, SysRole> implements ISysRoleService {

    @Autowired
    ISysRoleMenuService sysRoleMenuService;

    @Autowired
    ISysRoleDeptService sysRoleDeptService;

    @Override
    public PageVo queryPage(Map<String, Object> params) {

        String roleName = (String)params.get("roleName");

        IPage<SysRole> page = this.page(
                new PageQueryUtil<SysRole>().getPage(params),
                new QueryWrapper<SysRole>()
                        .like(StringUtils.isNotBlank(roleName),"role_name", roleName)
                );

        return new PageVo(page);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void saveRole(SysRole role) {
        role.setCreateTime(new Date());
        this.save(role);

        //保存角色与菜单关系
        sysRoleMenuService.saveOrUpdate(role.getRoleId(), role.getMenuIdList());

        //保存角色与部门关系
        sysRoleDeptService.saveOrUpdate(role.getRoleId(), role.getDeptIdList());
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void update(SysRole role) {
        this.updateById(role);

        //更新角色与菜单关系
        sysRoleMenuService.saveOrUpdate(role.getRoleId(), role.getMenuIdList());

        //保存角色与部门关系
        sysRoleDeptService.saveOrUpdate(role.getRoleId(), role.getDeptIdList());
    }
}
